package com.yitongmao.common;


import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.alibaba.sdk.android.oss_android_sdk.BuildConfig;
import com.yitongmao.common.reminder.ReaderApplication;
import com.yitongmao.core.aliyun.PutObjectUtils;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.AESCrypt;
import com.yitongmao.util.Loger;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;




public class UploadOSSService {
    private volatile static UploadOSSService instance;
    private ACache aCache;

    private OSS oss;
    private static String endpoint = "";
    private static String accessKeyId = "";
    private static String accessKeySecret = "";

    private static final String uploadFilePath = "";

    private static String mBucket = "";
    private static String uploadDir = "";
    private static String uploadFileSub = "";
    private static String webRoot = "";
    private static String picRoot = "";

    private boolean isInitSucess = false;

    private UploadParamsResponse uploadParamsResponse;
    private UploadEnCodingResponse uploadParamsResponse1;
    private String key = "newaircloud_vjow9Dej#JDj4[oIDF";
    private ACache mCache;

    private UploadOSSService() {
        mCache = ACache.get(ReaderApplication.getInstace());
    }

    public static UploadOSSService getInstance() {
        if (instance == null) {
            synchronized (UploadOSSService.class) {
                if (instance == null) {
                    instance = new UploadOSSService();
                }
            }
        }
        return instance;
    }

//    public OSS getOssInstance() {
//        return oss;
//    }
//
//    public String getPicRoot() {
//        return picRoot;
//    }
//
//    public String getUploadFileSub() {
//        return uploadFileSub;
//    }
//
//    public String getUploadDir() {
//        return uploadDir;
//    }
//
//    public String getmBucket() {
//        return mBucket;
//    }
//
//    public String getAccessKeyId() {
//        return accessKeyId;
//    }


    private String getUrl(String sid) {
        StringBuilder builder = new StringBuilder();
        builder.append(BuildConfig.APPLICATION_ID)
                .append("getOSSInfo?")
                .append("sid=" + sid);

        return builder.toString();
    }

    public boolean initialized(String sid, final CallBackListener mCallBackListener) {
        uploadParamsResponse = (UploadParamsResponse) mCache.getAsObject( key);
        boolean isCall = false;
        if (uploadParamsResponse != null) {
            initUploadParams(uploadParamsResponse);
            isCall = true;
            isInitSucess = true;
            mCallBackListener.onSuccess(true);
        }
        final boolean finalIsCall = isCall;
        BaseService.getInstance().simpleGetRequest(getUrl(sid), new CallBackListener<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(String result) {

                if (result != null && result.length() > 0 && result.startsWith("{") && result.endsWith("}")) {
                    uploadParamsResponse1 = UploadEnCodingResponse.objectFromData(result);
                    try {
                        String message = AESCrypt.decrypt(key, uploadParamsResponse1.info);
                        uploadParamsResponse = UploadParamsResponse.objectFromData(message);
                        mCache.put(key, uploadParamsResponse);
//                        System.out.print(message);
                    } catch (Exception e) {
                        System.out.print(e.toString());
                        isInitSucess = false;
                    }
                    if (!finalIsCall) {
                        initUploadParams(uploadParamsResponse);
                        mCallBackListener.onSuccess(true);
                    }
                    isInitSucess = true;
                } else {
                    onFail(null);
                }
            }

            @Override
            public void onFail(String result) {
                if (!finalIsCall) {
                    isInitSucess = false;
                    mCallBackListener.onFail(false);
                }
            }
        });
        return isInitSucess;
    }

    public void initUploadParams(UploadParamsResponse response) {
        if (response != null) {
            endpoint = response.endpoint;
            accessKeyId = response.accessKeyId;
            accessKeySecret = response.accessKeySecret;
            mBucket = response.bucket;
            uploadDir = response.uploadDir;
            uploadFileSub = response.uploadFile;
            webRoot = response.webRoot;
            picRoot = response.picRoot;
            try {
                OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);

                ClientConfiguration conf = new ClientConfiguration();
                conf.setConnectionTimeout(30 * 1000); // 连接超时，默认15秒
                conf.setSocketTimeout(30 * 1000); // socket超时，默认15秒
                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
                OSSLog.enableLog();
                oss = new OSSClient(ReaderApplication.getInstace(), endpoint, credentialProvider, conf);
            } catch (Exception e) {
                isInitSucess = false;
            }
        }
    }

    public void uploadPhotos(final HashMap<String, String> uploadFilesPaths, final CallBackListener callBackListener) {
        if (accessKeyId == null || accessKeyId.length() <= 0) {
            if (callBackListener != null)
                callBackListener.onFail("初始化失败");
        }
        final HashMap<String, String> uploadFilesPathsTemp = new HashMap<>();

        if (uploadFilesPaths != null && uploadFilesPaths.size() > 0) {
            Iterator iter = uploadFilesPaths.entrySet().iterator();
            int i = 0;
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = entry.getKey().toString();
                String uploadFilePath = entry.getValue().toString();

                uploadFilesPathsTemp.put(uploadFilePath, key);

                if (uploadFilePath.length() >= 4) {
                    final String dis = uploadFilePath.substring(uploadFilePath.length() - 4, uploadFilePath.length());
                    final String uploadPath = uploadDir + uploadFileSub + "_" + i + dis;
                    ++i;
                    Loger.d("uploadPath", "uploadPath-> " + uploadPath);
                    final HashMap<String, String> resultHashMap = new HashMap<>();
                    if (!uploadFilePath.startsWith("http")) {
                        PutObjectUtils.getInstance(oss, mBucket).asyncPutObjectFromLocalFile(uploadPath, uploadFilePath, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                Loger.d("PutObject", "UploadSuccess");
                                Loger.d("getUploadFilePath", request.getUploadFilePath());
                                Loger.d("ETag", result.getETag());
                                Loger.d("RequestId", result.getRequestId());
                                Loger.d("getStatusCode", result.getStatusCode() + "");

                                if (result.getStatusCode() == 200) {
                                    try {
                                        String resultImagePath = picRoot + "/" + uploadPath;
                                        resultHashMap.put(uploadFilesPathsTemp.get(request.getUploadFilePath()), resultImagePath);
                                        Loger.i("uploadUserHead", "uploadUserHead-resultImagePath:" + resultImagePath);

                                        callBackListener.onSuccess(resultHashMap);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                                if (callBackListener != null) {
                                    // 请求异常
                                    if (clientExcepion != null) {
                                        // 本地异常如网络异常等
                                        clientExcepion.printStackTrace();
//                                        callBackListener.onFail(clientExcepion.getMessage());
                                        callBackListener.onFail(null);
                                    }
                                    if (serviceException != null) {
                                        // 服务异常
                                        Loger.e("ErrorCode", serviceException.getErrorCode());
                                        Loger.e("RequestId", serviceException.getRequestId());
                                        Loger.e("HostId", serviceException.getHostId());
                                        Loger.e("RawMessage", serviceException.getRawMessage());

                                        callBackListener.onFail(null);
                                    }

                                }
                                isInitSucess = false;
                            }
                        }, new OSSProgressCallback<PutObjectRequest>() {
                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                Loger.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                            }
                        });
                    } else {
                        resultHashMap.put(key, uploadFilePath);
                        callBackListener.onSuccess(resultHashMap);
                    }
                }
            }
        }
    }

    public void uploadVideos(final HashMap<String, String> uploadFilesPaths, final CallBackProgressListener callBackProgressListener) {
        if (accessKeyId == null || accessKeyId.length() <= 0) {
            if (callBackProgressListener != null)
                callBackProgressListener.onFail("初始化失败");
        }
        final HashMap<String, String> uploadFilesPathsTemp = new HashMap<>();

        if (uploadFilesPaths != null && uploadFilesPaths.size() > 0) {
            Iterator iter = uploadFilesPaths.entrySet().iterator();
            int i = 0;
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = entry.getKey().toString();
                String uploadFilePath = entry.getValue().toString();

                uploadFilesPathsTemp.put(uploadFilePath, key);

                if (uploadFilePath.length() >= 4) {
                    final String dis = uploadFilePath.substring(uploadFilePath.length() - 4, uploadFilePath.length());
                    final String uploadPath = uploadDir + uploadFileSub + "_" + i + dis;
                    ++i;
                    Loger.d("uploadPath", "uploadPath-> " + uploadPath);
                    final LinkedHashMap<String, String> resultHashMap = new LinkedHashMap<>();
                    if (!uploadFilePath.startsWith("http")) {
                        PutObjectUtils.getInstance(oss, mBucket).asyncPutObjectFromLocalFile(uploadPath, uploadFilePath, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                Loger.d("PutObject", "UploadSuccess");
                                Loger.d("getUploadFilePath", request.getUploadFilePath());
                                Loger.d("ETag", result.getETag());
                                Loger.d("RequestId", result.getRequestId());
                                Loger.d("getStatusCode", result.getStatusCode() + "");

                                if (result.getStatusCode() == 200) {
                                    try {
                                        String resultImagePath = picRoot + "/" + uploadPath;
                                        resultHashMap.put(uploadFilesPathsTemp.get(request.getUploadFilePath()), resultImagePath);
                                        Loger.i("uploadUserHead", "uploadUserHead-resultImagePath:" + resultImagePath);

                                        callBackProgressListener.onSuccess(resultHashMap);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                                if (callBackProgressListener != null) {
                                    // 请求异常
                                    if (clientExcepion != null) {
                                        // 本地异常如网络异常等
                                        clientExcepion.printStackTrace();
//                                        callBackListener.onFail(clientExcepion.getMessage());
                                        callBackProgressListener.onFail(null);
                                    }
                                    if (serviceException != null) {
                                        // 服务异常
                                        Loger.e("ErrorCode", serviceException.getErrorCode());
                                        Loger.e("RequestId", serviceException.getRequestId());
                                        Loger.e("HostId", serviceException.getHostId());
                                        Loger.e("RawMessage", serviceException.getRawMessage());

                                        callBackProgressListener.onFail(null);
                                    }

                                }
                                isInitSucess = false;
                            }
                        }, new OSSProgressCallback<PutObjectRequest>() {
                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                Loger.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                                double progress = ((double)currentSize / (double) totalSize) * 100;
                                Loger.d("PutObject", "progress: " + progress);
                                callBackProgressListener.onProgress((int)progress, "video");
                            }
                        });
                    } else {
                        resultHashMap.put(key, uploadFilePath);
                        callBackProgressListener.onSuccess(resultHashMap);
                    }
                }
            }
        }
    }


}
